import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'dart:ui';

import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/config/route/common_widget_route.dart';
import 'package:dk_flutter_module_sale/phoenix/api/revision_main_api.dart';
import 'package:dk_flutter_module_sale/phoenix/main_tabbar/main_tabbar_page.dart';
import 'package:dk_flutter_module_sale/phoenix/my_setting/bean/bean_my_info.dart';
import 'package:dk_flutter_module_sale/phoenix/my_setting/bean/bean_update.dart';
import 'package:dk_flutter_module_sale/phoenix/my_setting/widget/widget_header_title.dart';
import 'package:dk_flutter_module_sale/phoenix/my_setting/widget/widget_my_info_header.dart';
import 'package:dk_flutter_module_sale/phoenix/my_setting/widget/widget_navigation_bar.dart';
import 'package:dk_flutter_module_sale/phoenix/my_setting/widget/widget_title_cell.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/bean/bean_tools_category.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/bean/bean_tools_item.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/widget/widget_tools_item.dart';
import 'package:dk_flutter_module_sale/sale/api/sale_in_api.dart';
import 'package:flutter/services.dart';

class MySettingPage extends CommonPage {
  final EventBus clickTabBarEventBus;
  MySettingPage({this.clickTabBarEventBus}) : super();
  @override
  void onInitState(CommonPageBloc pageBloc, {Map<String, Bloc> extraBlocMap}) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
    pageBloc.pageHttpGet(
        path: RevisionMainApi.personCenter,
        widgetBuilderByData: (dynamic data) {
          DataBean dataBean = DataBean.fromJson(data);
          return MySettingWidget(pageBloc,dataBean,clickTabBarEventBus: this.clickTabBarEventBus,);
        }
    );
  }
}

class MySettingWidget extends StatefulWidget {
  final EventBus clickTabBarEventBus;
  final CommonPageBloc pageBloc;
  final DataBean dataBean;
  MySettingWidget(this.pageBloc,this.dataBean,{this.clickTabBarEventBus});
  @override
  MeSettingState createState() {
    return MeSettingState(this.pageBloc,this.dataBean,clickTabBarEventBus: this.clickTabBarEventBus);
  }
}

class MeSettingState extends State<MySettingWidget> with SingleTickerProviderStateMixin,AutomaticKeepAliveClientMixin {
  final EventBus clickTabBarEventBus;
  CommonPageBloc meSettingBloc;
  DataBean dataBean;
  RefreshRedDotBloc redDotBloc = RefreshRedDotBloc();
  MeSettingState(this.meSettingBloc,this.dataBean,{this.clickTabBarEventBus});
  EventBus eventBus = EventBus();
  double _topBarOpacity = 0;
  @override
  void initState() {
    super.initState();
    this.clickTabBarEventBus.on<ClickTabBarEvent>().listen((ClickTabBarEvent event){
      if(event.clickPage == TabBarPage.TabBarPageMySetting){
        SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
        refreshPage();
      }
    });
    //打点我的
    UserTrack.trackViewScreen("公共我的-新", null);
    this.meSettingBloc.dataHttpGet(
        path: SaleInApi.updateVersionUrl,
        queryMap: {},
        handleResult: (dynamic data){
          UpdateBean updateBean = UpdateBean.fromJson(data);
          bool isNeedUpdate = (updateBean.needUpgrade == 1);
          if(isNeedUpdate) {
            this.redDotBloc.dispatch(isNeedUpdate) ;
          }
        },
        showLoading: false
    );
    FlutterBoost.singleton.addBoostContainerLifeCycleObserver((
        ContainerLifeCycle state, BoostContainerSettings settings) {
      if(settings.name != CommonWidgetRoute.COMMON_REVISION_HOME) {
        return;
      }
      if(state == ContainerLifeCycle.Appear) {
        refreshPage();
      } else if(state == ContainerLifeCycle.Destroy) {
        FlutterBoost.singleton.observersHolder.removeObserver(this);
      }
    });
  }

  Future<void> refreshPage() async {
    this.widget.pageBloc.dataHttpGet(
        showLoading: false,
        path: RevisionMainApi.personCenter,
        handleResult: (dynamic data) {
          setState(() {
            this.dataBean = DataBean.fromJson(data);
          });
        }
    );
  }

  void floatNavigationBar(ScrollNotification scroll) {
    // 当前滑动距离
    double currentExtent = scroll.metrics.pixels;
    double safeTop = MediaQueryData.fromWindow(window).padding.top;
    double height = 44 + safeTop;
    setState(() {
      if(currentExtent <= height) {
        _topBarOpacity = 0;
      } else {
        _topBarOpacity = (currentExtent - height) / height > 1.0 ? 1.0 : (currentExtent - height) / height;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    int totalCount = this.dataBean.list.length + 4;
    return NotificationListener(
      onNotification: (ScrollNotification note){
        //保持顶部沉浸式体验
        double offset = note.metrics.pixels.toDouble();
        RefreshNavigationBarEvent even = RefreshNavigationBarEvent(offset: offset);
        this.eventBus.fire(even);
        //悬浮
        this.floatNavigationBar(note);
        return true;
      },
      child: Stack(
        children: <Widget>[
          Container(
            color: Colors.white,
            child: ListView.builder(
                padding:EdgeInsets.only(top: 0) ,
                itemCount: totalCount,
                itemBuilder:this.itemBuilder()),
          ),
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: TopDynamicHeightWidget(offset: 0,eventBus: this.eventBus,),
          ),
          NavigationBar(topBarOpacity:this._topBarOpacity,)
        ],
      ),
    );
  }
  IndexedWidgetBuilder itemBuilder() {
    IndexedWidgetBuilder itemBuilder = (BuildContext context,int index){
      int totalCount = this.dataBean.list.length + 4;
      if(index == 0) {
        return HeaderTitleWidget();
      } else if(index == 1) {
        return MyInfoWidget(
          userInfoBean: this.dataBean.userInfo,
          onTapHeader: (){
            UserTrack.track("click_my_information", null);
            RouteUtil.goPage("dankegongyu://app/portal/mine/detail");
          },
        );
      } else if(totalCount -1 == index) {
        return Container(
          decoration: BoxDecoration(
              border: Border(bottom: BorderSide(width: 10,color: Color(0xFFF5F5F5)))
          ),
          child: BlocBuilder(
              bloc: this.redDotBloc,
              builder: (BuildContext context,bool showRedDot) {
                return TitleWidget(
                  hiddenBottomLine: true,
                  isShowRedDot: showRedDot,
                  title: "版本信息",
                  onTap: (){
                    UserTrack.track("click_my_version", null);
                    RouteUtil.goPage("dankegongyu://app/portal/mine/buildInfo");
                  },
                );
              }),
        );
      } else if(totalCount -2 == index) {
        TitleWidget titleWidget = TitleWidget(
            title: "设置",
            onTap: (){
              UserTrack.track("click_my_settings", null);
              RouteUtil.goPage("dankegongyu://app/portal/mine/setting");
            });
        return (this.dataBean.list.length > 0) ? Container(child: titleWidget,
            decoration:BoxDecoration(
                border: Border(top: BorderSide(width: 10,color: Color(0xFFF5F5F5)))
            ))
            :titleWidget;
      } else {
        ModulesListBean listBean = dataBean.list[index - 2];
        return ToolsModuleWidget(
          //leftSpacing: 28,
          //mainAxisSpacing: 28,
          bottomSpacing: 10,
          headChild: ToolsCommonTitleWidget(listBean.moduleName),
          data: listBean.tools,
          itemOnTap:(ToolsItem item){
            RouteUtil.goPage(item.appRouteUrl);
          } ,
        );
      }
    };
    return itemBuilder;
  }

  @override
  void dispose() {
    super.dispose();
    this.redDotBloc.dispose();
    this.eventBus.destroy();
    this.meSettingBloc.dispose();
  }

  @override
  bool get wantKeepAlive => true;
}

class RefreshRedDotBloc extends EventBloc<bool> {
  @override
  // TODO: implement initialState
  bool get initialState => false;
}